package com.asia5b.a5mall.member.activity

import android.text.TextUtils
import androidx.databinding.Observable
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.resource.StrCons
import com.asia5b.a5mall.member.R
import com.asia5b.a5mall.member.databinding.ActivityNewaddressBinding
import com.asia5b.a5mall.member.fragment.SelectCountryPhoneCodeDF
import com.asia5b.a5mall.member.fragment.SelectRegion2DF
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.event.AddressListDataChange
import com.asia5b.a5mall.middleware.logic.viewmodel.member.NewAddressActivityVM
import com.asia5b.a5mall.middleware.model.member.AddressModel
import com.asia5b.a5mall.middleware.model.member.CountryModel
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.middleware.widget.CancelSureViewModel
import kotlinx.android.synthetic.main.activity_newaddress.*

/**
 * Created by zhangyuncai on 2020/1/8.
 * @Note   地址修改添加页面
 */
@Route(path = ActCons.NewAddressActivity)
class NewAddressActivity : SimpleActivity<NewAddressActivityVM, ActivityNewaddressBinding>() {
    override val viewModelClazz: Class<NewAddressActivityVM>
        get() = NewAddressActivityVM::class.java

    override fun getDataBinding(): ActivityNewaddressBinding {
        val serializableAddress = intent.getSerializableExtra("address")
        if (serializableAddress != null) {
            address = serializableAddress as AddressModel
        } else {
            address = AddressModel()
        }
        type = intent.getStringExtra("type")!!
        return ActivityNewaddressBinding.inflate(layoutInflater)
    }

    override var sIsDark = true
    var type: String = StrCons.ADDRESS_ADD
    var address = AddressModel()

    override fun initView() {
        if (type == StrCons.ADDRESS_ADD) {
            head_addressedit.setTitleName(R.string.新增收货地址)
            head_addressedit.setRithtText("")
        } else {
            head_addressedit.setTitleName(R.string.编辑收货地址)
            head_addressedit.setRithtText(R.string.删除)
            //删除地址
            head_addressedit.setRightClickListener {
                CancelSureViewModel(mActivity, R.string.您确订要删除此收货地址) {
                    mViewModel.deleteAddress(address.addr_id)
                }.show()
            }
        }
        if (address.addr_id == 0) {
            //默认中国
            address.grOb.set("+86")
            address.defaultAddressOb.set(false)
        } else {
            address.nameOb.set(address.name)
            address.mobileOb.set(address.mobile)
            address.grOb.set("+" + address.gr)
            address.detailAddressOb.set(address.addr)
            address.labelOb.set(address.ship_address_name)
            address.regionTextOB.set("${address.countryName} ${address.provinceName} ${address.cityName} ${address.townName}")
            address.defaultAddressOb.set(address.isDefault)
        }
        mDataBinding.params = address

        setSubmitState()
    }

    fun setSubmitState() {
        bt_newaddress_save.isEnabled = true

        if (TextUtils.isEmpty(address.nameOb.get())) {
            bt_newaddress_save.isEnabled = false
            return
        }
        if (TextUtils.isEmpty(address.mobileOb.get())) {
            bt_newaddress_save.isEnabled = false
            return
        }
        if (address.countryId == -1 || address.provinceId == -1 || address.cityId == -1) {
            bt_newaddress_save.isEnabled = false
            return
        }
        if (TextUtils.isEmpty(address.detailAddressOb.get())) {
            bt_newaddress_save.isEnabled = false
            return
        }
    }

    override fun initEvent() {
        // 选择区号
        ll_select_country_code.setOnClickListener {
            InputMethodUtils.closeKeyBoard(mActivity)
            val selectPhoneCodeDF = SelectCountryPhoneCodeDF()
            selectPhoneCodeDF.show(supportFragmentManager, localClassName)
            selectPhoneCodeDF.setSureClick<CountryModel> {
                address.grOb.set("+${it.country_code}")
            }
        }

        //选择地区
        ll_newaddress_area.setOnClickListener {
            InputMethodUtils.closeKeyBoard(mActivity)
            val selectRegion2DF = SelectRegion2DF()
            selectRegion2DF.selectAddressModel = address
            selectRegion2DF.show(supportFragmentManager, "selectRegion2DF")
            selectRegion2DF.setSureClick<AddressModel> { selectAddressModel ->
                if (selectAddressModel != null) {

                    //国家/州/城市/城镇 并不是一一对应
                    address.countryName = selectAddressModel.countryName
                    address.countryId = selectAddressModel.countryId
                    address.provinceName = selectAddressModel.provinceName
                    address.provinceId = selectAddressModel.provinceId
                    address.cityName = selectAddressModel.cityName
                    address.cityId = selectAddressModel.cityId
                    address.townName = selectAddressModel.townName
                    address.townId = selectAddressModel.townId
                    address.regionTextOB.set("${address.countryName} ${address.provinceName} ${address.cityName} ${address.townName}")
                }
            }

        }
        val changeCallback = object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                setSubmitState()
            }

        }
        address.nameOb.addOnPropertyChangedCallback(changeCallback)
        address.mobileOb.addOnPropertyChangedCallback(changeCallback)
        address.detailAddressOb.addOnPropertyChangedCallback(changeCallback)
        //保存
        bt_newaddress_save.setOnClickListener {
            if (TextUtils.isEmpty(address.nameOb.get())) {
                showMessage(getString(R.string.请输入收货人姓名))
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(address.mobileOb.get())) {
                showMessage(getString(R.string.请输入手机号))
                return@setOnClickListener
            }
            if (address.countryId == -1 || address.provinceId == -1 || address.cityId == -1) {
                showMessage(getString(R.string.请选择收货地区))
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(address.detailAddressOb.get())) {
                showMessage(getString(R.string.请输入详细地址))
                return@setOnClickListener
            }

            val map = hashMapOf<String, Any>()
            map["id"] = address.addr_id
            map["name"] = address.nameOb.get()!!
            map["addr"] = address.detailAddressOb.get()!!
            map["gr"] = address.grOb.get()!!.replace("+", "")
            map["mobile"] = address.mobileOb.get()!!
            map["def_addr"] = if (address.defaultAddressOb.get()!!) 1 else 0
            if (!TextUtils.isEmpty(address.labelOb.get())) {
                map["ship_address_name"] = address.labelOb.get()!!
            }
            map["region"] = (address.townId <= 0).judge(address.cityId, address.townId)
            when (type) {
                StrCons.ADDRESS_ADD -> {
                    mViewModel.addAddress(map)
                }
                StrCons.ADDRESS_EDIT -> {
                    mViewModel.editAddress(map)
                }
            }
        }
    }

   override fun startObserver()
    {
        mViewModel.addAddressResultLiveData.observe(this, Observer {
            addAddressResult()
        })
        mViewModel.addAddressErrorLiveData.observe(this, Observer {
            addAddressError(it.errResultModel!!.code, it.errResultModel!!.message)
        })
    }

    override fun initData() {

    }

    fun addAddressResult() {
        getEventBus().post(AddressListDataChange())
        finish()
    }

    fun addAddressError(errorCode: String, errorMsg: String) {
        if (errorCode == "101") {
            // 默认收货地址不能更改
            switch_address.isChecked = true
            address.isDefault = switch_address.isChecked
        }
    }
}